package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 保存setmeal套餐表 同时保存setmeal_dish菜品表
     * 从setmeal套餐表获取setmeal的id 将id保存到setmeal表里
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "SetmealCache",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto){

        setmealService.saveWithDish(setmealDto);

        return R.success("保存成功");
    }

    @PutMapping
    public R<String> update(@RequestBody SetmealDto setmealDto){

        setmealService.updateByDish(setmealDto);

        return R.success("修改成功");
    }

    @GetMapping("{id}")
    public R<SetmealDto> getByDish(@PathVariable Long id){

        SetmealDto setmealByDish = setmealService.getByDish(id);

        return R.success(setmealByDish);
    }
    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize,String name){

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(name!=null, Setmeal::getName,name)
                .orderByDesc(Setmeal::getUpdateTime);

        Page<Setmeal> setmealPage = new Page<>(page,pageSize);

        setmealService.page(setmealPage,queryWrapper);

        Page<SetmealDto> setmealDtoPage = new Page<>();

        BeanUtils.copyProperties(setmealPage,setmealDtoPage,"records");

        List<SetmealDto> list = setmealPage.getRecords().stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();

            BeanUtils.copyProperties(item, setmealDto);

            Long categoryId = setmealDto.getCategoryId();

            String categoryName = categoryService.getById(categoryId).getName();

            if (categoryName != null) {
                setmealDto.setCategoryName(categoryName);
            }

            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(list);

        return R.success(setmealDtoPage);
    }

    @DeleteMapping()
    @CacheEvict(value = "SetmealCache",allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids ){

        setmealService.deleteByIds(ids);

        return R.success("删除成功");
    }

    @GetMapping("/list")
    @Cacheable(value = "SetmealCache",key = "#setmeal.categoryId+'_'+#setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal){

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getCategoryId,setmeal.getCategoryId())
                .eq(Setmeal::getStatus,1)
                .orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> setmealList = setmealService.list(queryWrapper);
        return R.success(setmealList);
    }

    @Transactional
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status,@RequestParam List<Long> ids){
            log.info("收到的状态码为：{}，需要删掉的套餐ID集合为：{}",status,ids);

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.in(Setmeal::getId,ids);

        for (Setmeal setmeal : setmealService.list(queryWrapper)) {
            setmeal.setStatus(status);
            setmealService.updateById(setmeal);
        }
        return R.success("修改状态成功");
    }
}
